package com.zxl.template.activity;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.VpnService;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.view.View;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.example.sslvpn_android_client.VPNServiceManager;
import com.zxl.template.App;
import com.zxl.template.R;
import com.zxl.template.adapter.TbVPAdapter;
import com.zxl.template.base.BaseAty;
import com.zxl.template.base.BaseFrag;
import com.zxl.template.base.IActivity;
import com.zxl.template.fragment.ContactFrag;
import com.zxl.template.fragment.DocFrag;
import com.zxl.template.fragment.NCollectFrag;
import com.zxl.template.fragment.QueryFrag;
import com.zxl.template.fragment.SettingFrag;
import com.zxl.template.http.JsonCallback;
import com.zxl.template.model.Doc;
import com.zxl.template.model.DocParams;
import com.zxl.template.model.MsgEvent;
import com.zxl.template.view.NoTouchViewPager;
import com.zxl.template.view.pop.VpnLoginPop;
import com.zxl.zlibrary.tool.LActivityTool;
import com.zxl.zlibrary.tool.LCacheTool;
import com.zxl.zlibrary.tool.LEmptyTool;
import com.zxl.zlibrary.tool.LToast;
import com.zxl.zlibrary.tool.LogTool;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import me.majiajie.pagerbottomtabstrip.NavigationController;
import me.majiajie.pagerbottomtabstrip.PageNavigationView;
import me.majiajie.pagerbottomtabstrip.item.BaseTabItem;
import me.majiajie.pagerbottomtabstrip.item.NormalItemView;
import okhttp3.Call;

import static com.zxl.template.constant.constant.BROADCAST_VPN_SERVICE;

public class MainActivity extends BaseAty implements IActivity {
    private static final String TAG = "MainActivity";


    //data
    List<BaseFrag> fragments = new ArrayList<>();
    NavigationController mNavigationController;


    @BindView(R.id.tab_viewpager)
    NoTouchViewPager tabViewpager;
    @BindView(R.id.pageBottomTabLayout)
    PageNavigationView pageBottomTabLayout;
    @BindView(R.id.loading)
    View loading;

    private boolean otherApp = false;
    public VPNServiceManager mVpn = null;
    private ProgressDialog vpnPd;
    private String account;
    private String password;

    @SuppressLint("SdCardPath")
    private final static String vpnPath = "/data/data/com.zxl.template/vpn";
    private boolean hasExtra = false;
    private String data;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        if (!EventBus.getDefault().isRegistered(this))
            EventBus.getDefault().register(this);

        requestPermissions();
        ButterKnife.bind(this);

        initOtherApp();


        if (!otherApp) {
            initView();
            initData();
            initListener();
        }
    }

    /**
     * 处理外部APP调用的方法
     */
    @SuppressLint("WrongConstant")
    private void initOtherApp() {
        Intent intent = getIntent();
        if (!hasExtra) {
            hasExtra = intent.hasExtra("data");
        }
        if (hasExtra) {
            otherApp = true;
            loading.setVisibility(View.VISIBLE);

            LCacheTool cacheTool = LCacheTool.getInstance(new File(vpnPath));
            account = cacheTool.getString("account");
            password = cacheTool.getString("password");

            if (LEmptyTool.isEmpty(account) && LEmptyTool.isEmpty(password)) {
                openPop();
            } else {
                if (LEmptyTool.isEmpty(vpnPd)) {
                    vpnPd = ProgressDialog.show(this, "", "初始化...", true);
                }

                if (LEmptyTool.isEmpty(data)) {
                    Bundle bundle = intent.getExtras();
                    assert bundle != null;
                    data = bundle.getString("data");
                }

                mApi.username = data;
                mApi.password = "123456";
                mApi.initApi("172.16.113.190");

                mVpn = VPNServiceManager.getVpnServiceManager();
                mVpn.addBroadcastReceiver(BROADCAST_VPN_SERVICE);
                mVpn.addHandler(handler);


                //启动vpn服务
                intent = VpnService.prepare(this);
                if (intent != null) {
                    startActivityForResult(intent, 0);
                } else {
                    onActivityResult(0, RESULT_OK, null);
                }
            }

        } else {
            otherApp = false;
        }
    }

    private void openPop() {
        VpnLoginPop vpnLoginPop = new VpnLoginPop(this);
        vpnLoginPop.showPopupWindow();

        vpnLoginPop.setBtnOnClickListener(i -> {
            if (i == 1) {
                finish();
            } else if (i == 2) {
                initOtherApp();
            }
        });

    }

    @Override
    public void initView() {
        fragments.clear();
        fragments.add(DocFrag.getInstance());
        fragments.add(QueryFrag.getInstance());
        if (!otherApp)
            fragments.add(ContactFrag.getInstance());
        fragments.add(NCollectFrag.getInstance());
        if (!otherApp)
            fragments.add(SettingFrag.getInstance());


        if (!otherApp)
            mNavigationController = pageBottomTabLayout.custom()
                    .addItem(newItem(R.mipmap.ic_doc_normal, R.mipmap.ic_doc_select, "公文"))
                    .addItem(newItem(R.mipmap.ic_query_normal, R.mipmap.ic_query_select, "查询"))
                    .addItem(newItem(R.mipmap.ic_contact_normal, R.mipmap.ic_contact_select, "通讯"))
                    .addItem(newItem(R.mipmap.ic_collect_normal, R.mipmap.ic_collect_select, "收藏"))
                    .addItem(newItem(R.mipmap.ic_setting_normal, R.mipmap.ic_setting_select, "设置"))
                    .build();
        else
            mNavigationController = pageBottomTabLayout.custom()
                    .addItem(newItem(R.mipmap.ic_doc_normal, R.mipmap.ic_doc_select, "公文"))
                    .addItem(newItem(R.mipmap.ic_query_normal, R.mipmap.ic_query_select, "查询"))
//                    .addItem(newItem(R.mipmap.ic_contact_normal, R.mipmap.ic_contact_select, "通讯"))
                    .addItem(newItem(R.mipmap.ic_collect_normal, R.mipmap.ic_collect_select, "收藏"))
//                    .addItem(newItem(R.mipmap.ic_setting_normal, R.mipmap.ic_setting_select, "设置"))
                    .build();

        tabViewpager.setOffscreenPageLimit(5);
        tabViewpager.setAdapter(new TbVPAdapter(getSupportFragmentManager(), fragments));
        //自动适配ViewPager页面切换
        mNavigationController.setupWithViewPager(tabViewpager);

        initNum();
    }

    private void initNum() {
        mApi.docList(this, 1, new JsonCallback<Doc>() {
            @Override
            public void onError(Call call, Exception e, int i) {
                LogTool.e(TAG, e);
            }

            @Override
            public void onResponse(Doc doc, int i) {
                //设置消息数
                mNavigationController.setMessageNumber(0, doc.total);
            }
        });
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(MsgEvent<DocParams> event) {
        if (event.type.equals("refresh_doc_list")) {
            initNum();

            //vpn异常
        } else if (event.type.equals("reVpn")) {
            vpnPd.show();
            initOtherApp();
        }
    }


    @Override
    public void initListener() {

    }


    @Override
    public void initData() {


    }


    //创建一个Item
    private BaseTabItem newItem(int drawable, int checkedDrawable, String text) {
        NormalItemView normalItemView = new NormalItemView(this);
        normalItemView.initialize(drawable, checkedDrawable, text);
        normalItemView.setTextDefaultColor(0xFF333333);
        normalItemView.setTextCheckedColor(0xFF007DFE);
        return normalItemView;
    }

    private void requestPermissions() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (checkSelfPermission(Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
                // Permission has not been granted and must be
                // requested.
                shouldShowRequestPermissionRationale(Manifest.permission.READ_PHONE_STATE);
                requestPermissions(
                        new String[]{Manifest.permission.READ_PHONE_STATE},
                        1);
            }
        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        if (requestCode == 0 && resultCode == RESULT_OK) {
            mVpn.authWithAccount(MainActivity.this, "222.221.245.174", 6443, account, password);
        }
    }


    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            JSONObject json = JSON.parseObject((String) msg.obj);
            int type = json.getInteger("type");
            int result = json.getInteger("result");
            String reason = json.getString("reason");


            LogTool.e(TAG + "：" + result + "，" + reason);
            //登录成功
            if (result == 2001) {
                initView();
                initData();
                initListener();
                if (LEmptyTool.isNotEmpty(vpnPd) && vpnPd.isShowing())
                    vpnPd.dismiss();
                loading.setVisibility(View.GONE);
            } else if (result == 10000) {
                LogTool.e(TAG + "vpn10000：" + result + "，" + reason);
                int nextAuthentication = json.getInteger("nextAuthentication");
                if (nextAuthentication == VPNServiceManager.AUTHENTICATION_FINISH) {
                    App.mApp.mVpn.startVPNService(MainActivity.this);
                }
            } else if (result == 91) {
                vpnPd.dismiss();
                openPop();
            }
        }
    };


    @Override
    protected void onDestroy() {
        super.onDestroy();
        //关闭服务
        if (LEmptyTool.isNotEmpty(mVpn)) {
            mVpn.stopService(this);
            mVpn.removeHandler(handler);
        }

        if (!EventBus.getDefault().isRegistered(this)) EventBus.getDefault().unregister(this);
        if (LEmptyTool.isNotEmpty(vpnPd)) vpnPd.dismiss();

        if (LEmptyTool.isNotEmpty(App.mApp.mVpn)) App.mApp.mVpn.stopService(this);
    }

    @Override
    protected void onStop() {
        super.onStop();
        LogTool.e("----------stop------------");

    }

    @Override
    protected void onPause() {
        super.onPause();
        LogTool.e("----------pause------------");
    }


    @Override
    public void onBackPressed() {
        super.onBackPressed();
        finish();
    }
}
